package com.ygxsk.carhome.ui.care;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.dialogx.dialogs.PopTip;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventBusQRCode;
import com.ygxsk.carhome.event.EventCardDistHistory;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.CouponCustomer;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.CardDistHistoryAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-25  20:05
 * @Description:卡券核销历史记录：是人员和卡券的时间 等历史记录；   餐券-核销记录，
 * 2024年1月22日17:52:47 因为改造，这块已经不能用了，只剩下代码参考。
 */
public class CardDistHistoryActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutindisthistory)
    SmartRefreshLayout refreshLayoutInDistHistory;

    @BindView(R.id.recyclerviewindisthistory)
    RecyclerView recyclerViewInDistHistory;

//    //选择类型
//    @BindView(R.id.nice_spinner_cartype)
//    NiceSpinnersk nice_spinner_carType;
//    //选择来源
//    @BindView(R.id.nice_spinner_formwhere)
//    NiceSpinnersk nice_spinner_formWhere;
//    //选择状态
//    @BindView(R.id.nice_spinner_stateitem)
//    NiceSpinnersk nice_spinner_stateItem;

    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<>();


    private CardDistHistoryAdapter cardDistHistoryAdapter;

    /**
     * 最后一条上传的id的信息内容
     */
    private int pagination_upLoad = Parameterkey.pageNum_default_first;
    //核销卡券 的弹窗内容，展示卡券的结果；

    //    private CustomDialog customDialog;
    //添加扫码核销的自定义弹窗；
    private MaterialDialog materialDialogCustomView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        mSession = Session.get(this);

        processExtraData();

//        if (dataListFromWhere == null) {
//            dataListFromWhere = new ArrayList<>();
//        }
//
//        if (dataListStateItem == null) {
//            dataListStateItem = new ArrayList<>();
//        }

        initloading();

        initViews();

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_card_dist_history;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.card_dist_history));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //核销的历史记录顶部啥都没有；
//      toolbarHelper.setLayoutRight(false, 0, "", null);

        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.scanqr_code_str), new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                //快速双加的限制，
//                // : 2023-07-25 21:39 携带二维码的信息;
//                Bundle bundle = new Bundle();
//                bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
//                bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY);
//                ActivityUtils.startActivity(bundle, MyBGAQRCodeActivity.class);
//
//            }
//        });


    }

    //根据扫描的二维码信息，获取餐券的信息接口
    private void method_gainData_by_qrCode_for_rice_ticked(String _rqCode_content) {

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "调用 餐券发放-餐券核销接口--method_gainData_by_qrCode_for_rice_ticked");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.couponCode, _rqCode_content);
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDLATENTCUSTOMER);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addLatentCustomer_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponDetailForManagerRiceTick(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomer>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<CouponCustomer>() {
                    @Override
                    public void accept(CouponCustomer couponCustomer) throws Throwable {

                        //获取完毕这个优惠券的信息之后，展示这个优惠券的信息；
                        if (couponCustomer != null) {
                            method_show_dist_dialog(_rqCode_content, couponCustomer);
                        } else {
                            ToastUtils.showShort(getString(R.string.action_abnormal));
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //
                    }
                });


    }

    //扫码完毕立即执行的操作：上传二维码的信息,根据这个二维码的信息 获取这个优惠券的信息 做展示
    //这是跳转到-客户关怀的根据二维码获取 优惠券的详情
    private void method_gainData_by_qrCode_for_customer_care_card(String _rqCode_content) {

        //如果扫码的内容为空，那么需要提示
//        if (TextUtils.isEmpty(_rqCode_content)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
//            CommUtils.checkDialog(mAlertView);
//            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
//            mAlertView.show();
//            return;
//        }

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "调用客户关怀-优惠券核销接口--method_gainData_by_qrCode_for_customer_care_card");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.couponCode, _rqCode_content);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDLATENTCUSTOMER);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addLatentCustomer_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponDetailForManager(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomer>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<CouponCustomer>() {
                    @Override
                    public void accept(CouponCustomer couponCustomer) throws Throwable {

                        //获取完毕这个优惠券的信息之后，展示这个优惠券的信息；
                        if (couponCustomer != null) {
                            method_show_dist_dialog(_rqCode_content, couponCustomer);
                        } else {
                            ToastUtils.showShort(getString(R.string.action_abnormal));
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //
                    }
                });

    }

    //弹窗的操作：展示获取到的优惠券的信息；
    private void method_show_dist_dialog(String _rqCode_content, CouponCustomer _couponCustomer) {

        View viewCard = View.inflate(mActivityInstance, R.layout.popu_card_dist_middle_popu, null);

        if (viewCard != null) {

            //标题 卡券的
            TextView textViewCardName = (TextView) viewCard.findViewById(R.id.textviewcardname);
            //卡券的备注 使用简介
            TextView textViewCardLittleInfo = (TextView) viewCard.findViewById(R.id.textviewcardlittleinfo);
            //使用范围
            TextView textViewCardUseRangeInfo = (TextView) viewCard.findViewById(R.id.textviewcarduserangeinfo);
            //卡券的有效期
            TextView textViewCardTime = (TextView) viewCard.findViewById(R.id.textviewcardtime);
            //卡券的有效期
            RoundTextView textViewCardCancel = (RoundTextView) viewCard.findViewById(R.id.textviewcardcancel);
            //卡券的取消按钮
            RoundTextView textViewCardSure = (RoundTextView) viewCard.findViewById(R.id.textviewcardsure);

            //填充优惠券名称
            textViewCardName.setText(_couponCustomer.getCouponName());
            textViewCardLittleInfo.setText(_couponCustomer.getCouponLowAmountInfo());

            if (!TextUtils.isEmpty(_couponCustomer.getUseRangeInfo())) {
                textViewCardUseRangeInfo.setVisibility(View.VISIBLE);
                textViewCardUseRangeInfo.setText(_couponCustomer.getUseRangeInfo());
            } else {
                textViewCardUseRangeInfo.setVisibility(View.GONE);
                //textViewCardUseRangeInfo.setText(_couponCustomer.getUseRangeInfo());
            }
            textViewCardTime.setText(_couponCustomer.getEndTime());

            if (textViewCardCancel != null) {
                textViewCardCancel.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        //此时 弹窗是已经被弹出的
                        if (materialDialogCustomView != null) {
                            materialDialogCustomView.dismiss();
                        }

                    }
                });
            }

            if (textViewCardSure != null) {
                textViewCardSure.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        // : 2023-08-16 21:07 这才是真实的核销二维码卡券的接口

                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                            method_gainAddSubmitInfo_upLoad_for_rice_ticked(_rqCode_content);

                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                            method_gainAddSubmitInfo_upLoad_for_care_customer_card(_rqCode_content);

                        }

                    }
                });
            }

            //激发 弹窗弹出内容
            materialDialogCustomView = new MaterialDialog.Builder(CardDistHistoryActivity.this)
                    .customView(viewCard, false)
                    .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                    //.positiveText("确定")
                    .positiveColor(ColorUtils.getColor(R.color.dark))
                    //.negativeText("取消")
                    .canceledOnTouchOutside(false)
                    .show();

            //materialDialog.getTitleView().setTextSize(16f);

        }

    }

    @Override
    protected void onClickNodata(View v) {
        gainDatas();
    }

    @Override
    protected void initViews() {

        //----------------------------------------------------------------------------------
        //布局的适配器填充，下拉刷新等等；
        recyclerViewInDistHistory.setLayoutManager(new MyLinearLayoutManager(this));

        cardDistHistoryAdapter = new CardDistHistoryAdapter(R.layout.card_dist_history_adapter, mDataResources);
        recyclerViewInDistHistory.setAdapter(cardDistHistoryAdapter);

        cardDistHistoryAdapter.notifyDataSetChanged();

        cardDistHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                // : 2023-07-13 15:07 跳转到这个客户的详情页面??
//                Bundle extra_bundle = new Bundle();
//                extra_bundle.putParcelable(ExtraKey.EXTRA_RUNMANGROUPMANAGEBEAN, runManGroupManageBeanItem);
//                ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);

            }
        });

        cardDistHistoryAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                if (couponCustomerVo != null) {

                    switch (view.getId()) {

                        case R.id.textviewdistcustomerphone: {//拨打

                            //因为要上传编号 业务类型，故要区分开；
                            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                                clickButton_toCallPhone(CardDistHistoryActivity.this, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_8.getIndex());

                            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                                clickButton_toCallPhone(CardDistHistoryActivity.this, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());

                            }

                            break;
                        }

                        default:
                            break;
                    }
                }

            }
        });

        refreshLayoutInDistHistory.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {


                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                            getServerDatas_for_rice_tick_history();

                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                            getServerDatas();

                        } else {
                            //额外的
                            getServerDatas();
                        }

                        refreshLayout.finishLoadMore();
                    }
                });
            }
        });

//        if (roundButtonAddGroupInRunManGroup != null) {
//            roundButtonAddGroupInRunManGroup.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
//                @Override
//                public void onDebouncingClick(View v) {
//
//                    // : 2023-07-13 15:52 跳转到人员分配列表页面
//                    //跳转到资产的添加页面
//                    Bundle extra_bundle = new Bundle();
////
////                    //String shopId = assetInSideBean.getShopId();
////
////                    //是添加进来的
////                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE,ExtraValue.VALUE_JUMP_FORM_ASSET_ADD);
////
////                    extra_bundle.putString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID,assetInSideBean.getShopId());
////
////                    //携带服务站的列表过去
////                    extra_bundle.putParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET, assetStationInfoListForAddAsset);
////                    //携带资产的归属方
////                    extra_bundle.putParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE, assetUnderBusinessInfoListOutSide);
////                    //
//                    ActivityUtils.startActivity(extra_bundle, LeadManagerGroupActivity.class);
//
//                }
//            });
//        }

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        pagination_upLoad = Parameterkey.pageNum_default_first;

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            //判断是从 客户关怀过来还是从-餐券发放过来
            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                getServerDatas_for_rice_tick_history();

            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                getServerDatas();

            } else {
                //额外的
                getServerDatas();
            }

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInDistHistory, false);
        }

    }


    //餐券发放-的核销餐券接口
    private void method_gainAddSubmitInfo_upLoad_for_rice_ticked(String _codeMessage) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.couponCode, _codeMessage);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERCOUPONFORVERIFY_RICKET);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerCouponForVerify_ricket_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateCustomerCouponForVerify_Ricket(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        CommUtils.checkMaterialDialog(materialDialog);

                        //核销弹窗是要有信息的
                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        method_handler_dist_success();

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                });

    }


    //执行上传操作:客户关怀页面，的卡券核销 这个二维码卡券；
    private void method_gainAddSubmitInfo_upLoad_for_care_customer_card(String _codeMessage) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.couponCode, _codeMessage);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERCOUPONFORVERIFY);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //核销弹窗消失？
                        //核销弹窗是要有信息的
                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        method_handler_dist_success();

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                });

    }

    //卡券核销成功之后的处理值,通用；
    private void method_handler_dist_success() {

        //只有提交成功 关闭这个核销弹窗
        CommUtils.checkMaterialDialog(materialDialog);
        CommUtils.checkMaterialDialog(materialDialogCustomView);

        //通知主页列表刷新
        EventCardDistHistory eventCardDistHistory = new EventCardDistHistory();
        eventCardDistHistory.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_DIST_HISTORY_MAIN_LIST);
        EventBus.getDefault().post(eventCardDistHistory);

        PopTip.show("核销成功").iconSuccess();

    }

    //获取餐券的核销历史页
    private void getServerDatas_for_rice_tick_history() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETGETCUSTOMERCOUPONFORVERIFY_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getGetCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getGetCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));
                        }
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInDistHistory, true);
                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    private void getServerDatas() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COUPONCUSTOMERVOOUTSIDE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));
                        }
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInDistHistory, true);
                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });


    }

    private void method_handler_success(CouponCustomerVoOutSide _couponCustomerVoOutSide) {

        if (_couponCustomerVoOutSide != null) {

            ArrayList<CouponCustomerVo> couponCustomerVos = _couponCustomerVoOutSide.getDataList();

            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {
                if (mDataResources != null) {
                    mDataResources.addAll(couponCustomerVos);
                }
            }
        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDataResources != null && mDataResources.isEmpty()) {
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
        }

        pagination_upLoad = _couponCustomerVoOutSide.getNextPagination();

        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
            setFinishLoadMoreWithNoMoreData(refreshLayoutInDistHistory, true);
        } else {
            setEnableLoadmore(refreshLayoutInDistHistory, true);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCardDist(EventCardDistHistory eventCardDistHistory) {

        if (eventCardDistHistory != null) {

            if (eventCardDistHistory.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_DIST_HISTORY_MAIN_LIST) {

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardDistHistoryAdapter != null) {
                    cardDistHistoryAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadCardDistHistory(EventBusQRCode eventBusQRCode) {

        if (eventBusQRCode != null) {

            if (eventBusQRCode.getMessage() == ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY) {

                //2024年1月15日11:13:30 餐券和卡券是通用一个历史记录

                String qrCodeResult = eventBusQRCode.getContent();

//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "接收到的扫码核销值为：-->" + qrCodeResult);
                //32c48fe0534459bc63d3098c53142ed3
                //AUTOSTEWARD_3ad891e251455ab46ad60d8f571f2cd74d

                if (!TextUtils.isEmpty(qrCodeResult)) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "qrCodeResult：-->" + qrCodeResult);

                    if (qrCodeResult.startsWith(Parameterkey.QRCODE_PREFIX)) {

                        //如果扫码的内容为空，那么需要提示
                        //这是跳转到-客户关怀的根据二维码获取 优惠券的详情
                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                            // TODO: 2024/1/22 17:50  改造之后这块废弃,不从这里核销
                            method_gainData_by_qrCode_for_rice_ticked(qrCodeResult);

                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                            method_gainData_by_qrCode_for_customer_care_card(qrCodeResult);

                        } else {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "没有执行-调用核销码 获取详情接口");
                        }

                    } else if (qrCodeResult.contains(Parameterkey.QRCODE_HTTP)) {
                        CommUtils.linkJumpDialog(CardDistHistoryActivity.this, CardDistHistoryActivity.this, qrCodeResult);
                    } else {
                        CommUtils.textJumpDialog(CardDistHistoryActivity.this, CardDistHistoryActivity.this, qrCodeResult);
                    }

                } else {

                    if (TextUtils.isEmpty(qrCodeResult)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
                        mAlertView.show();
                    }

                }

            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
            cardDistHistoryAdapter = null;
        }

        CommUtils.checkMaterialDialog(materialDialogCustomView);

        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);

            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);

            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);

        }

    }
}